package com.suo.enroll.utils;

import org.codehaus.jettison.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;

public class OCRUtils {

    final static String clientId = "ACm1VXL4KW3SCdKOOl30oDUi";
    final static String clientSecret = "Iir1rUyxo1nMFQuBeGLy6xzmdyTOVcYf";

    private static String token = null;
    private static String getToken() {
        // 授权服务地址
        String authUrl = "https://aip.baidubce.com/oauth/2.0/token";

        // 请求参数
        String params = "grant_type=client_credentials"
                + "&client_id=" + clientId
                + "&client_secret=" + clientSecret;

        try {
            // 创建URL对象
            URL url = new URL(authUrl);
            // 打开HTTP连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 发送请求参数
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(params.getBytes());
            outputStream.flush();
            outputStream.close();

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                Scanner scanner = new Scanner(connection.getInputStream());
                StringBuilder response = new StringBuilder();
                while (scanner.hasNext()) {
                    response.append(scanner.nextLine());
                }
                scanner.close();

                // 将响应解析为 JSON 对象
                JSONObject jsonResponse = new JSONObject(response.toString());
                // 从 JSON 中提取 access_token
                String accessToken = jsonResponse.getString("access_token");

                // 返回 access_token
                return accessToken;
            } else {
                throw new RuntimeException("Failed : HTTP error code : " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String ocr(MultipartFile image) {
        // 百度OCR API的URL
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
        try {
            // 将MultipartFile转换为字节数组
            byte[] imgData = image.getBytes();
            // 将字节数组进行Base64编码
            String imgStr = Base64Util.encode(imgData);
            // 将编码后的图片参数进行URL编码
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            // 设置请求参数
            String param = "image=" + imgParam;
            // TODO
            // 注意，这里仅为了简化编码每次请求都去获取access_token，线上环境请缓存token，避免频繁请求
            //TODO
            if (token == null) {
                token = getToken();
            }
            String accessToken = token;

            // 发送POST请求到百度OCR API并获取结果
            String result = HttpUtil.post(url, accessToken, param);

            // 打印并返回OCR结果
            return result;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
